'use client';

import { type ChangeEvent, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { search } from '@/services/api';
import Link from 'next/link';
import useToast from '@/hooks/useToast';
import type { IPagination, IPost, IQueryParams } from '@/interfaces';
import Alert from '@/app/[locale]/alert/alert';
import useModal from '@/hooks/useModal';
import classNames from 'classnames';
import AlertLoad from '@/app/[locale]/alert/load';
import { useTranslations } from 'use-intl';
import Nodata from '@/app/[locale]/common/nodata/nodata';

export default function SearchModal({ mid }: { mid?: string | undefined }) {
  const [name, setName] = useState('');
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
    size: 10,
  });
  const { hideModal } = useModal();
  const { show } = useToast();
  const t = useTranslations('SearchPage');

  const searchQuery = useQuery(
    ['/search', name, params],
    async (context) => {
      return (await search({
        query: {
          ...(context.queryKey[2] as any),
          name: encodeURIComponent(context.queryKey[1] + ''),
        },
      })) as IPagination<IPost>;
    },
    {
      enabled: !!(name && name.length > 1),
      keepPreviousData: true,
    },
  );

  function onClickLink() {
    hideModal(mid);
  }

  function onClickClose() {
    hideModal(mid);
  }

  function onClickPrevious() {
    const data = searchQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: t('dataNotExists'),
      });
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = searchQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: t('dataNotExists'),
      });
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  function onChangeName(e: ChangeEvent<HTMLInputElement>) {
    setName(e.target.value);
  }

  return (
    <>
      <div className="modal-header">
        <h1 className="modal-title fs-5 hstack align-items-center">
          {t('search')}
        </h1>
        <button
          onClick={onClickClose}
          type="button"
          className="btn-close"
          aria-label="Close"
        ></button>
      </div>
      <div className="modal-body">
        <div className="vstack gap-4">
          <input
            name="name"
            value={name}
            onChange={onChangeName}
            className="form-control"
            type="search"
            placeholder={t('pleaseEnterSearchContent')}
            aria-label="name"
          />

          {searchQuery.data && (
            <div className="vstack gap-4">
              {searchQuery.data.content.length > 0 && (
                <div className="card">
                  <div className="card-header user-select-none">
                    {t('relatedData')}
                  </div>
                  <div className="list-group list-group-flush">
                    {searchQuery.data.content.map((item) => {
                      return (
                        <Link
                          key={item.id}
                          href={`/posts/${item.id}`}
                          onClick={onClickLink}
                          className="list-group-item list-group-item-action"
                        >
                          {item.name}
                        </Link>
                      );
                    })}
                  </div>
                </div>
              )}

              {searchQuery.data.content.length === 0 && <Nodata />}

              {searchQuery.data.pageable.pages > 1 && (
                <nav>
                  <ul className="pagination justify-content-end">
                    <li
                      className={classNames(
                        'page-item',
                        searchQuery.data.pageable.previous ? false : 'disabled',
                      )}
                    >
                      <a
                        onClick={onClickPrevious}
                        className="page-link cursor-pointer"
                      >
                        {t('previousPage')}
                      </a>
                    </li>
                    <li
                      className={classNames(
                        'page-item',
                        searchQuery.data.pageable.next ? false : 'disabled',
                      )}
                    >
                      <a
                        onClick={onClickNext}
                        className="page-link cursor-pointer"
                      >
                        {t('nextPage')}
                      </a>
                    </li>
                  </ul>
                </nav>
              )}
            </div>
          )}

          {searchQuery.isError && (
            <Alert message={searchQuery.error} type="error" />
          )}

          {name && name.length > 1 && searchQuery.isLoading && <AlertLoad />}

          <div></div>
        </div>
      </div>
    </>
  );
}
